#include "irc.h"

/* addNode should allocate memory for added leaf
 * and copy the added leaf to the allocated memory
 * this needs to traverse through the whole tree
 * if necessary so that the tree will stay sorted
 *
 * return 0 on success
 */
/* does not consider the root node to be empty */
int addNode(Node *root, Node *leaf) {
	int dir;
	Node *ptr;
	dir = strcmp(root->command, leaf->command);
	/* root is less than leaf, so put leaf to the right */
	if (dir < 0) {
		if (root->right == NULL ) /* got room */
		{
			ptr = calloc(1, sizeof(struct node));
			memcpy(ptr, leaf, sizeof(struct node));
			root->right = ptr;
			ptr->parent = root;
		} else {
			addNode(root->right, leaf);
		}
	}
	/* root is more than leaf, so put leaf to the left */
	else if (dir > 0) {
		if (root->left == NULL ) /* got room */
		{
			ptr = calloc(1, sizeof(struct node));
			memcpy(ptr, leaf, sizeof(struct node));
			root->left = ptr;
			ptr->parent = root;
		} else {
			addNode(root->left, leaf);
		}
	}
	/* leaf command is the same as root command, so maybe just add the handler?
	 * to be done at a later time
	 */
	else {
		return 1;
	}
	return 0;
}

/* delNode must free previously allocated memory
 * for requested leaf, and must maintain sorted
 * tree structure
 *
 * return 0 on success
 */
int delNode(Node *root, Node *leaf) {
	return 0;
}

/* findNode will traverse through given root
 * Node assuming the tree is sorted.
 *
 * returns a pointer to the node if found,
 * NULL otherwise
 */
Node *findNode(Node *root, char *key) {
	int dir;
	void *fp = NULL;
//	printf("findNode called\n");
	dir = strcmp(root->command, key);
	if (dir < 0) /* right */
	{
		fp = findNode(root->right, key);
	} else if (dir > 0) /* left */
	{
		fp = findNode(root->left, key);
	} else {
		return root;
	}
	return fp;
}
